go to previous page   go to home page   go to next page hear noise

Answer:

The completed program is given below.


Complete Program

flowchart

Here is the complete program that adds up even and odd integers from zero the limit, N, specified by the user:

import  java.util.Scanner;

// User enters a value N
// Add up odd integers,  
// even  integers, and all integers 1 to N
//
class AddUpIntegers
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    int N, sumAll = 0, sumEven = 0, sumOdd = 0;

    System.out.print( "Enter limit value: " );
    N = scan.nextInt();

    int count = 1;
    while (  count <= N )    
    {
      sumAll = sumAll + count ;
      
      if ( count % 2 == 0  )
        sumEven = sumEven + count ;

      else
        sumOdd  = sumOdd  + count ;

      count = count + 1 ;
    }

    System.out.print  ( "Sum of all : " + sumAll  );
    System.out.print  ( "\tSum of even: " + sumEven );
    System.out.println( "\tSum of odd : " + sumOdd  );
  }
}

It would be odd if you did not copy and paste this program to Notepad, save it to a file, and run it. An even better idea would be to pretend you had not seen it, and to try to create it from scratch.


QUESTION 7:

Which is larger: the sum of evens or the sum of odds? Does the answer to this question change if N is even or odd?